package cn.wizzer.app.cms.modules.services.impl;

import cn.wizzer.app.cms.modules.models.CmsBanner;
import cn.wizzer.app.cms.modules.services.CmsBannerService;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.base.model.enums.BizExceptionEnum;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import com.alibaba.dubbo.config.annotation.Service;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.plugins.wkcache.annotation.CacheDefaults;
import org.nutz.plugins.wkcache.annotation.CacheRemoveAll;
import org.nutz.plugins.wkcache.annotation.CacheResult;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@IocBean(args = {"refer:dao"})
@Service(interfaceClass = CmsBannerService.class)
@CacheDefaults(cacheName = "cms_banner")
public class CmsBannerServiceImpl extends BaseServiceImpl<CmsBanner> implements CmsBannerService {
    public CmsBannerServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    @CacheRemoveAll
    public void removeCache() {
    }

    /**
     * Banner校验逻辑
     *
     * @param cmsBanner Banner
     * @return boolean
     */
    public Result validateBanner(CmsBanner cmsBanner) {
        // 名称校验
        if (Strings.isBlank(cmsBanner.getName())) {
            return Result.error(BizExceptionEnum.NAME_CAN_NOT_BE_NULL);
        }
        // 图片不能为空
        if (Strings.isBlank(cmsBanner.getPicture())) {
            return Result.error(BizExceptionEnum.PICTURE_CAN_NOT_BE_NULL);
        }
        return Result.success();
    }

    @Override
    @CacheResult
    public List<CmsBanner> queryByLanguage(String language, String type) {

        // todo 暂时性增加类型判断
        // 类型为空时，默认类型为BANNER
        if (Strings.isBlank(type)) {
            return this.query(Cnd.where("language","=",language).and("type","=","BANNER").and("disabled","=",0).orderBy("sort","ASC"));
        }
        // 类型为OTHER 将PLAY_RULE一起查询
        else if ("OTHER".equals(type)){
            return this.query(Cnd.where("language","=",language).and(Cnd.exps("type", "=", "OTHER").or("type", "=", "PLAY_RULE")).and("disabled","=",0).orderBy("sort","ASC"));
        }
        return this.query(Cnd.where("language","=",language).and("type","=",type).and("disabled","=",0).orderBy("sort","ASC"));
    }
}
